import 'package:xvideos/tools_base/net/net_manager.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/text_util.dart';
import 'package:sprintf/sprintf.dart';

class DateTimeUtil {
  ///计算当前时间差值
  static int calTime3(String? date) {
    if (TextUtil.isEmpty(date) || date?.contains("0001-01-01") == true) return -1;
    //解析时间
    var time = DateTime.parse(utc2iso(date)).toLocal();
    //计算时间差
    var difference = time.difference(DateTime.now());
    return difference.inSeconds;
  }

  ///日期时间本地格式化
  static String utc2iso(String? formattedString) {
    if (formattedString == null || formattedString.isEmpty) return '';
    try {
      DateTime dateTime = DateTime.parse(formattedString).toLocal();
      String? y = _fourDigits(dateTime.year);
      String? m = _twoDigits(dateTime.month);
      String? d = _twoDigits(dateTime.day);
      String? h = _twoDigits(dateTime.hour);
      String? min = _twoDigits(dateTime.minute);
      String? sec = _twoDigits(dateTime.second);
      return "$y-$m-$d $h:$min:$sec";
    } catch (e) {
      return '';
    }
  }

  ///日期时间本地格式化
  static String utc2isoMD(String? formattedString) {
    if (formattedString == null || formattedString.isEmpty) return '';
    try {
      DateTime dateTime = DateTime.parse(formattedString).toLocal();
      String? m = _twoDigits(dateTime.month);
      String? d = _twoDigits(dateTime.day);
      return "$m月$d日";
    } catch (e) {
      return '';
    }
  }

  ///2020-11-26T17:44:45.000Z
  static String? format2utc(DateTime dateTime) {
    String? y = _fourDigits(dateTime.year);
    String? m = _twoDigits(dateTime.month);
    String? d = _twoDigits(dateTime.day);
    String? h = _twoDigits(dateTime.hour);
    String? min = _twoDigits(dateTime.minute);
    String? sec = _twoDigits(dateTime.second);
    String? ms = _threeDigits(dateTime.millisecond);
    return "$y-$m-${d}T$h:$min:$sec.${ms}Z";
  }

  static String? _fourDigits(int n) {
    int absN = n.abs();
    String? sign = n < 0 ? "-" : "";
    if (absN >= 1000) return "$n";
    if (absN >= 100) return "${sign}0$absN";
    if (absN >= 10) return "${sign}00$absN";
    return "${sign}000$absN";
  }

  static String? _threeDigits(int n) {
    if (n >= 100) return "$n";
    if (n >= 10) return "0$n";
    return "00$n";
  }

  static String? _twoDigits(int n) {
    if (n >= 10) return "$n";
    return "0$n";
  }

  ///utc 转 年月日
  static String utcTurnYear(String? date, {String? char, bool? isChina, bool showHM = false}) {
    if (date == null || date.isEmpty) return '';
    String? gap = char ?? "-";
    DateTime dateTime = DateTime.parse(date).toLocal();
    String? y = _fourDigits(dateTime.year);
    String? m = _twoDigits(dateTime.month);
    String? d = _twoDigits(dateTime.day);
    String? hour = _twoDigits(dateTime.hour);
    String? min = _twoDigits(dateTime.minute);
    if (isChina == true) {
      return "$y年$m月$d日";
    }
    if (showHM == true) {
      return "$y$gap$m$gap$d $hour:$min";
    }
    return "$y$gap$m$gap$d ";
  }

  ///utc 转 月日
  static String? utc2MonthDay(String? date) {
    if (date == null || date.isEmpty) return '';
    try {
      DateTime dateTime = DateTime.parse(date).toLocal();
      String? m = _twoDigits(dateTime.month);
      String? d = _twoDigits(dateTime.day);
      return "$m-$d ";
    } catch (e) {
      return '';
    }
  }

  ///utc 转 时、分
  static String? utc2HourMinute(String? date) {
    if (date == null || date.isEmpty) return '';
    try {
      DateTime dateTime = DateTime.parse(date).toLocal();
      String? h = _twoDigits(dateTime.hour);
      String? m = _twoDigits(dateTime.minute);
      return "$h-$m ";
    } catch (e) {
      return '';
    }
  }

  static String utc3YearMonthDay(DateTime dateTime) {
    try {
      String? y = _twoDigits(dateTime.year);
      String? m = _twoDigits(dateTime.month);
      String? d = _twoDigits(dateTime.day);
      return "$y-$m-$d ";
    } catch (e) {
      return '';
    }
  }

  ///计算时间差值
  static String? calTime(String? date, DateTime? serverTime) {
    //解析时间
    var time = DateTime.parse(date ?? "").toLocal();
    //计算时间差
    var difference = time.difference(serverTime ?? DateTime.now());

    String? day = difference.inDays.toString();
    String? hours = (difference.inHours % 24).toString();
    String? minutes = (difference.inMinutes % 60).toString();
    return "${day}_${hours}_$minutes";
  }

  ///计算字符串时间差值
  static String? calTimediffFromNow(String? date) {
    //解析时间
    var time = DateTime.parse(date ?? "").toLocal();
    var now = DateTime.now();
    //计算时间差
    var difference = time.difference(now);
    String? day = difference.inDays.toString();
    String? hours = (difference.inHours % 24).toString();
    return '$day天$hours小时';
  }

  static String? futureTime(int seconds) {
    //解析时间
    DateTime date = DateTime.now();
    DateTime dateFuture = date.add(Duration(seconds: seconds));
    String? y = _fourDigits(dateFuture.year);
    String? m = _twoDigits(dateFuture.month);
    String? d = _twoDigits(dateFuture.day);
    String? hour = _twoDigits(dateFuture.hour);
    String? min = _twoDigits(dateFuture.minute);
    String? sec = _twoDigits(dateFuture.second);
    return "$y-$m-$d $hour:$min:$sec";
  }

  static String? formatDuration(Duration position) {
    final ms = position.inMilliseconds;

    int seconds = ms ~/ 1000;
    final int hours = seconds ~/ 3600;
    seconds = seconds % 3600;
    var minutes = seconds ~/ 60;
    seconds = seconds % 60;

    final hoursString = hours >= 10
        ? '$hours'
        : hours == 0
            ? '00'
            : '0$hours';

    final minutesString = minutes >= 10
        ? '$minutes'
        : minutes == 0
            ? '00'
            : '0$minutes';

    final secondsString = seconds >= 10
        ? '$seconds'
        : seconds == 0
            ? '00'
            : '0$seconds';

    final formattedTime = '${hoursString == '00' ? '' : '$hoursString:'}$minutesString:$secondsString';

    return formattedTime;
  }

  /// 转换时间格式，例如：01:20:54、20:54
  static String getTimeText(double seconds) {
    var duration = Duration(milliseconds: (seconds * 1000).toInt());

    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(Duration.minutesPerHour));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(Duration.secondsPerMinute));

    var str = "$twoDigitMinutes:$twoDigitSeconds";

    if (duration.inHours == 0) {
      return str;
    }
    //FIXME:移除时间补齐
    var hour = duration.inHours.toString(); //.padLeft(2, "0");
    return "$hour:$str";
  }

  //判断是否过期
  static bool isExpireDate(String? time) {
    if (TextUtil.isNotEmpty(time)) {
      DateTime dateTime = DateTime.parse(time!);
      return dateTime.isAfter((netManager.getFixedCurTime()));
    }
    return false;
  }
}

/// 构建时分秒`00:00:00`
String buildHHMMSS(int seconds) {
  int hour = seconds ~/ 3600;
  int minute = (seconds ~/ 60) % 60;
  int second = seconds % 60;
  return _formatTime(hour) + ":" + _formatTime(minute) + ":" + _formatTime(second);
}

/// 构建分秒`00:00:00`
String buildMMSS(int seconds) {
  int minute = seconds ~/ 60;
  int second = seconds % 60;
  return _formatTime(minute) + ":" + _formatTime(second);
}

//数字格式化，将 0~9 的时间转换为 00~09
String _formatTime(int timeNum) {
  return timeNum.toString().padLeft(2, '0');
}

///显示时间 [time] 秒 --->时间转换，例如：90  ->   01:30
String timePrint(double time) {
  double minute = 0;
  if (time >= 60) {
    minute = time / 60;
  }
  int second = time.toInt() % 60;
  var minute2 = minute.toInt();
  var str1 = (minute2 >= 10) ? minute2.toString() : "0${minute2.toString()}";
  var str2 = (second >= 10) ? second.toString() : "0${second.toString()}";
  return sprintf("%s:%s", [str1, str2]);
}

/// 显示规则：刚刚、几分钟前、几小时前、几天前、一周前、年月日,
String formatTime(String? utcTime, {String gap = "-", bool hasTimeGap = false}) {
  if (utcTime?.isNotEmpty != true) {
    return "近期";
  }
  var now = DateTime.now();
  var date = DateTime.parse(utcTime!).toLocal();
  final changeTime = now.difference(date); //秒

  int s = changeTime.inSeconds;
  if (s >= 0 && s < 60) {
    return "刚刚";
  }
  final int m = changeTime.inMinutes;
  if (m > 0 && m < 60) {
    return "${m + 1}分钟前";
  }
  final int h = changeTime.inHours;
  if (h > 0 && h < 24) {
    return "${h + 1}小时前";
  }
  final int d = changeTime.inDays;
  if (d > 0 && d < 7) {
    return "${d + 1}天前";
  }

  final int w = d ~/ 7;
  if (w > 0 && w < 4) {
    return "${w + 1}周前";
  }

  final int month = changeTime.inDays ~/ 12;
  if (month > 0) {
    // 显示 年月日
    String timeNow = date.yyyyMMDDFormat(gap: gap); //2018年09月16日 23时16分15秒
    return timeNow;
  }
  return "";
}

String formatTimeTwo(String? utcTime) {
  if (utcTime?.isNotEmpty != true) {
    return "近期";
  }
  var now = DateTime.now();
  var date = DateTime.parse(utcTime!).toLocal();
  int changeTime = (now.millisecondsSinceEpoch - date.millisecondsSinceEpoch) ~/ 1000; //秒

  final int s = changeTime;
  if (s >= 0 && s < 60) {
    return "刚刚";
  }
  final int m = s ~/ 60;
  if (m > 0 && m < 60) {
    return "$m分钟前";
  }
  final int h = m ~/ 60;
  if (h > 0 && h < 24) {
    return "$h小时前";
  }
  final int d = h ~/ 24;
  if (d > 0 && d < 7) {
    return "$d天前";
  }

  final int w = d ~/ 7;
  if (w > 0 && w < 4) {
    return "$w周前";
  }

  final int month = d ~/ 30;
  if (w >= 4 && month < 1) {
    return '1个月内';
  }

  if (month > 0 && month < 12) {
    return "$month个月前";
  }
  final int year = month ~/ 12;
  if (year > 0 && year < 12) {
    return "$year年前";
  }
  return "";
}
